package com.zb.job;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.zb.constant.WorkConstant;
import com.zb.entity.*;
import com.zb.service.*;
import com.zb.service.impl.ZjWorkDispatchEngineerServiceImpl;
import com.zb.utils.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.UUID;

/**
 * @Author WEN
 * @Date 2025/7/9 0009
 **/
@Slf4j
public class EngineerReceiveTimeoutJob implements Job {
    public EngineerReceiveTimeoutJob() {}

    public EngineerReceiveTimeoutJob(Long custAccId, Long workDispatchEngineerId, Long workDispatchNetworkId) throws SchedulerException {
        log.info("创建工程师接单超时任务:{}", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));

        ZjWorkSetService workSetService = SpringContextUtil.getBean(ZjWorkSetService.class);
        if (workSetService == null){
            log.error("获取工单设置服务失败");
            return;
        }

        ZjWorkSet workSet = workSetService.getById(custAccId);
        log.info("获取工单设置结果：{}", workSet);
        if (workSet == null)return;

        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

        JobDetail jobDetail = JobBuilder.newJob(EngineerReceiveTimeoutJob.class)
                .withIdentity("engineerReceiveTimeoutJob" + UUID.randomUUID())
                .usingJobData("workDispatchEngineerId", workDispatchEngineerId)
                .usingJobData("workDispatchNetworkId", workDispatchNetworkId)
                .build();

        Trigger trigger = TriggerBuilder.newTrigger()
                .startAt(DateBuilder.futureDate(workSet.getEngineerReceiveTimeout(), DateBuilder.IntervalUnit.HOUR))
                .build();

        scheduler.scheduleJob(jobDetail, trigger);

        scheduler.start();
    }
    @Override
    public void execute(JobExecutionContext jobExecutionContext){
        log.info("工程师超时未接单任务执行:{}", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));

        JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();
        long workDispatchEngineerId = jobDataMap.getLong("workDispatchEngineerId");
        log.info("工单分派工程师ID：{}", workDispatchEngineerId);

        ZjWorkDispatchEngineerService workDispatchEngineerService = SpringContextUtil.getBean(ZjWorkDispatchEngineerServiceImpl.class);
        if (workDispatchEngineerService == null){
            log.error("获取工单分配工程师服务失败");
            return;
        }

        ZjWorkDispatchEngineer workDispatchEngineer = workDispatchEngineerService.getById(workDispatchEngineerId);
        log.info("获取工单分配工程师结果：{}", workDispatchEngineer);
        if (workDispatchEngineer == null || workDispatchEngineer.getStatus() != WorkConstant.DISPATCH_ENGINEER_STATUS_1) return;

        ZjWorkDispatchNetworkService workDispatchNetworkService = SpringContextUtil.getBean(ZjWorkDispatchNetworkService.class);
        if (workDispatchNetworkService == null){
            log.error("获取工单分派网点服务失败"); return;
        }

        long workDispatchNetworkId = jobDataMap.getLong("workDispatchNetworkId");
        log.info("工单分派网点Id:{}", workDispatchNetworkId);

        ZjWorkDispatchNetwork workDispatchNetwork = workDispatchNetworkService.getById(workDispatchNetworkId);
        log.info("获取工单分派网点结果：{}", workDispatchNetwork);
        if (workDispatchNetwork == null || workDispatchNetwork.getStatus() != WorkConstant.DISPATCH_NETWORK_STATUS_3) return;

        log.info("修改工程师接单状态为拒绝结单");
        workDispatchEngineer.setStatus(WorkConstant.DISPATCH_ENGINEER_STATUS_6);
        workDispatchEngineerService.updateById(workDispatchEngineer);

        log.info("修改网点状态为待派工");
        workDispatchNetwork.setStatus(WorkConstant.DISPATCH_NETWORK_STATUS_2);
        workDispatchNetworkService.updateById(workDispatchNetwork);

        ZjWorkLogService workLogService = SpringContextUtil.getBean(ZjWorkLogService.class);
        if (workLogService == null){
            log.error("获取工单日志服务失败");
            return;
        }

        ZjNetworkEmpService networkEmpService = SpringContextUtil.getBean(ZjNetworkEmpService.class);
        if (networkEmpService == null){
            log.error("获取网点人员服务失败");
            return;
        }

        ZjAccountService accountService = SpringContextUtil.getBean(ZjAccountService.class);
        if (accountService == null){
            log.error("获取账号服务失败");
            return;
        }

        ZjNetworkEmp networkEmp = networkEmpService.getById(workDispatchEngineer.getNetworkEmpId());
        if (networkEmp == null) return;

        ZjAccount account = accountService.getById(networkEmp.getAccountId());
        if (account == null) return;

        log.info("记录工单日志");
        ZjWorkLog workLog = new ZjWorkLog();
        workLog.setId(IdWorker.getId());
        workLog.setCustAccId(workDispatchNetwork.getCustAccId());
        workLog.setWorkId(workDispatchNetwork.getWorkId());
        workLog.setType(6);
        workLog.setName("");
        workLog.setCreateEmp("");
        workLog.setEvent("工程师超时未接单");
        workLog.setContent("工程师【" +account.getName()+ "】超时未接单，待重新分派工程师");
        workLogService.save(workLog, new ArrayList<>());
    }
}
